package org.dyk.seamanshousefrontdesk.controller;

import com.alibaba.fastjson.JSONArray;
import org.dyk.seamanshousefrontdesk.model.User;
import org.dyk.seamanshousefrontdesk.service.cart.CartService;
import org.dyk.seamanshousefrontdesk.tools.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = {"/cart"})
public class CartController {
    @Autowired
    private CartService cartService;

    /**
     * 购物车 页面
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("")
    public String cart(HttpSession session, Model model){
        //获取当前用户信息，查询当前用户购物车信息
        User userData = (User) session.getAttribute(Constants.USER_SESSION);
        JSONArray allByUid = cartService.findAllByUid(userData.getUid());
        model.addAttribute("cartList",allByUid);
        return "cart";
    }

    /**
     * 添加购物车 验证
     * @param gid
     * @param session
     * @return
     */
    @RequestMapping("/insertCart")
    @ResponseBody
    public boolean insertCart(@RequestParam int gid, HttpSession session){
        //获取当前用户ID
        User userData = (User)session.getAttribute(Constants.USER_SESSION);
        boolean insert = cartService.insert(gid, userData.getUid());
        if (insert){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 删除购物车
     * @param gid
     * @return
     */
    @RequestMapping(value = {"/delete"})
    public String delete(@RequestParam int gid){
        boolean delete = cartService.delete(gid);
        if (delete){
            return "redirect:/cart";
        }else {
            return "redirect:/cart";
        }
    }

    /**
     * 修改购物车商品数量
     * @param cid
     * @param goodsNum
     * @return
     */
    @RequestMapping(value = {"/updataQuantity"})
    @ResponseBody
    public boolean updataQuantity(@RequestParam int cid, @RequestParam int goodsNum){
        //获取到购物车信息
        boolean b = cartService.updataQuantity(cid, goodsNum);
        if (b){
            return true;
        }else {
            return false;
        }
    }
}
